<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-08-29 15:27
 *
 * Version: 2.0
 */

namespace App\Lib\Logs;


use Illuminate\Support\Facades\DB;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class Logs
{
	public static function newFile($filename, $info)
	{
		$Filename = storage_path() . '/logs/' . date('Y-m-d', time()) . '-' . $filename . '.log';
		if (!file_exists($Filename)) {
			fopen($Filename, "w");
		}

		$log = new Logger('');
		$log->pushHandler(new StreamHandler($Filename, 0,true,0777));
		$ip = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : 'root';
		$api = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'root';

		$log->addInfo('ip:' .$ip. '   api:' .$api.'  '. $info);
	}

	/**
	 * sql 日志
	 */
	public static function sqlInfo($isAll = false)
	{
		if (config('app.sql_log')) {
			DB::listen(function ($query) use ($isAll) {
				$tmp = str_replace('?', '"' . '%s' . '"', $query->sql);
				$tmp = @vsprintf($tmp, $query->bindings);
				$tmp = str_replace("\\", "", $tmp);
				$action = substr($tmp, 0, 6);
				$patt = strpos($tmp, 'ims_tiny_wmall_action_log');
				if ($isAll) {
					$ip = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : 'root';
					$api = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'root';
						$info = 'ip:' .$ip. '   api:' .$api. '   execution time: ' . $query->time . 'ms; ' . $tmp . "\t";
				} else {
					//如果是更新删除操作则存储到数据库里
					if ($action == 'update' || $action == 'delete' || $action == 'insert' && !$patt) {
						$info =  'execution time: ' . $query->time . 'ms; ' . $tmp . "\t";
					}
				}
				if(isset($info)) self::newFile('sql', $info);
			});
		}
	}


	/**
	 * 异常日志
	 * @param $info
	 */
	public static function errorInfo($info)
	{
		if (config('app.error_log')) {
			self::newFile('error', $info);
		}
	}

	/**
	 * 正常日志
	 * @param $info
	 */
	public static function info($info)
	{
		if (config('app.laravel_log')) {
			self::newFile('info', $info);
		}
	}
}
